<?php
namespace app;

use Error;
use own\exception\TipsException;
use own\helps\RespCode;
use own\helps\OwnLogger;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\ClassNotFoundException;
use think\exception\Handle;
use think\exception\HttpException;
use think\exception\HttpResponseException;
use think\exception\RouteNotFoundException;
use think\exception\ValidateException;
use think\Response;
use Throwable;
use TypeError;
use Yansongda\Pay\Exception\Exception as PayException;

/**
 * 应用异常处理类
 */
class ExceptionHandle extends Handle
{
    /**
     * 不需要记录信息（日志）的异常类列表
     * @var array
     */
    protected $ignoreReport = [
        HttpException::class,
        HttpResponseException::class,
        ModelNotFoundException::class,
        DataNotFoundException::class,
        ValidateException::class,
    ];

    /**
     * 记录异常信息（包括日志或者其它方式记录）
     * @access public
     * @param  Throwable $exception
     * @return void
     */
    public function report(Throwable $exception): void
    {
        // 使用内置的方式记录异常日志
        parent::report($exception);
    }

    /**
     * Render an exception into an HTTP response.
     * @access public
     * @param \think\Request   $request
     * @param Throwable $e
     * @return Response
     */
    public function render($request, Throwable $e): Response
    {
        if ($e instanceof TipsException) {
            return $this->json($e->getMessage(), $e->getCode());
        }
        if ($e instanceof ValidateException) {
            return $this->json($e->getMessage(), RespCode::ERROR);
        }
        //支付异常
        if($e instanceof PayException) {
            OwnLogger::fatal($e->getMessage(), 'pay-exception');
            return $this->json('支付失败', RespCode::ERROR);
        }
        if ($e instanceof RouteNotFoundException) {
            return $this->json('未找到请求路径', RespCode::ROUTE_ERROR);
        }
        if ($e instanceof HttpException) {
            OwnLogger::warning($this->message($e));
            return $this->json($this->message($e), RespCode::ROUTE_ERROR);
        }
        if ($e instanceof TypeError) {
            return $this->json($this->message($e), RespCode::ERROR, RespCode::SYS_ERROR);
        }
        if ($e instanceof Error) {
            return $this->json($this->message($e), RespCode::ERROR, RespCode::SYS_ERROR);
        }
        if ($e instanceof ClassNotFoundException) {
            return $this->json($$this->message($e), RespCode::ERROR, RespCode::SYS_ERROR);
        }
        if ($e instanceof Exception) {
            OwnLogger::fatal($this->message($e));
            return $this->json($this->message($e), RespCode::ERROR, RespCode::SYS_ERROR);
        }
        // 其他错误交给系统处理
        OwnLogger::fatal($this->message($e));
        return parent::render($request, $e);
    }
    /**
     * @param string $message
     * @param integer $dataCode
     * @param integer $respCode
     */
    public function json($message, $dataCode, $respCode = 200): Response
    {
        if($respCode == 500) {
            OwnLogger::fatal($message);
        }
        return Response::create(['code' => $dataCode, 'message' => $message, 'data' => null], 'json', $respCode)->header([
            'Access-Control-Allow-Origin' => '*',
            'Access-Control-Allow-Methods' => 'POST,GET,PUT,DELETE,OPTIONS',
            'Access-Control-Allow-Headers' => 'X-Requested-With,Content-Type,Token,Authorization,X-Token',
            'Content-Type' => 'application/json; charset=utf-8',
            'Access-Control-Allow-Credentials' => 'false',
            'Access-Control-Max-Age' => 1800
        ]);
    }
    /**
     * 异常信息
     * @param Throwable $e
     */
    public function message(Throwable $e): string
    {
        return $e->getMessage() . '[' . $e->getFile() . ']:' . $e->getLine();
    }
}
